let bases = require('bases');
let generator = require('generate-password');
const crypto = require('crypto');
let speakeasy = require('speakeasy');
let QRCode = require('qrcode');
const request = require('request');
const BigNumber = require('bignumber.js');

let knox = require("knox");

const converSymbols = {}

const moment = require('moment');

const nodemailer = require('nodemailer');

let functions = {};

module.exports = functions;


functions.checkEmail = function (email) {
    // First check if any value was actually set
    if (email.length === 0) return false;
    // Now validate the email format using Regex
    let re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;
    return re.test(email);
};

functions.checkPhone = function (phone) {
    return true;
};

functions.generate_random_string = function (length, incl_uppercase) {
    if (length === undefined)
        length = 10;
    if (incl_uppercase === undefined)
        incl_uppercase = true;
    return generator.generate({
        length: length,
        numbers: true,
        uppercase: incl_uppercase,
        excludeSimilarCharacters: true
    });
};

functions.generate_transfer_code = function (user_id) {
    let user_component = bases.toBase32((user_id + 300000) % 1000000);
    let random_component = bases.toBase32(Math.random() * 300000);
    return user_component + random_component;
};

functions.checkError = async function (condition, message, returnOnSuccess) {
    if (condition)
        return returnOnSuccess
    throw Error(message)
};

functions.checkDigits = function (input, max_digits = 4) {
    if (!input) {
        return false;
    }
    if (input.toString().split('.')[1] && input.toString().split('.')[1].length > max_digits) {
        return false;
    }
    if (input.toString().split('.')[1] && input.toString().split('.')[1].indexOf('.') > -1) {
        return false;
    }
    return true;//input % (100000000 / Math.pow(10, max_digits)) === 0;
};


functions.currentTimestamp = function (date) {
    if (date) {
        return parseInt(moment(date).valueOf() / 1000);
    }
    return parseInt(moment().utcOffset(8).valueOf() / 1000);
};


functions.getTokenKey = function (type) {
    const uuid = require('uuid');
    const hmac = crypto.createHmac('sha256', uuid.v1() + new Date().getTime() + Math.floor(Math.random() * 100000000) + type);
    hmac.update(uuid.v1() + type);
    return hmac.digest('hex');
};

functions.toFloor = function (num, n = 2) {
    if (isNaN(num)) {
        return 0;
    }
    num = parseFloat(num);
    let d = functions.bigNumberDiv(Math.floor(functions.bigNumberMultipliedBy(num, (Math.pow(10, n)))), (Math.pow(10, n)));
    return d.toFixed(n);
};


functions.accMul = function (arg1, arg2) {
    let m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length;
    } catch (e) {
    }
    return (Number(s1.replace(".", "")) * Number(s2.replace(".", ""))) / Math.pow(10, m)
};


functions.getAddr = function (ip) {
    try {
        return new Promise(function (resolve, reject) {
            let assetsUrl = "https://restapi.amap.com/v3/ip?output=json";
            assetsUrl += '&key=' + 'd99275a74f73226bd60a706fba03d522';
            assetsUrl += '&ip=' + ip;

            const options = {
                timeout: 5000,
                method: 'GET',
                json: true,
                url: assetsUrl,
                headers:
                {
                    'cache-control': 'no-cache',
                    Connection: 'keep-alive',
                    Accept: '*!/!*',
                    'Content-Type': 'application/json'
                }
            };
            request(options, function (err, status, body) {
                if (body.status == "1") {
                    resolve(body.province + "-" + body.city)
                } else {
                    resolve("")
                }
            });
        });
    } catch (e) {
        resolve("")
    }
};

functions.validateEmail = function (email) {
    let regemail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    if (!regemail.test(email)) {
        return false;
    }
    return true;
};

functions.validatePhone = function (phone) {
    let regphone = /^[1][0-9][0-9]{9}$/;
    if (!regphone.test(phone)) {
        return false;
    }
    return true;
};

functions.checkIpAddr = function (ipaddr) {
    if (!ipaddr) {
        return false;
    }

    let ss = ipaddr.split(".");

    if (ss.length != 4) {
        return false;
    }

    let i = 0;
    for (i = 0; i < ss.length; i++) {
        if (isNaN(ss[i]) || parseInt(ss[i]) < 0 || parseInt(ss[i]) > 255) {
            return false;
        }
    }

    return true;
};

functions.addressCut = function (value) {
    if (value) {
        return value.substr(0, 8) + '...' + value.substr(value.length - 8, value.length)
    }
    return value;
};


functions.isChina = function (str) {
    let reg = /[\u4e00-\u9fa5]/g;
    if (reg.test(str)) {
        return true;
    } else {
        return false;
    }
};
